<?php

namespace App\Http\Controllers;


use App\Models\Communities;
use App\Models\District;
use Illuminate\Http\Request;

class CommunitiesController extends Controller
{
    public function index(Request $request)
    {
        $builder     = Communities::query()->with(['city', 'county']);
        $province_id = $request->input('province');
        if (isset($province_id)) {
            $params['province_id'] = $province_id;
            $params['cities']      = District::where('parentid', $province_id)->get();
            $builder->where('province_id', $province_id);
        }
        $city_id = $request->input('city');
        if (isset($city_id)) {
            $params['city_id']  = $city_id;
            $params['counties'] = District::where('parentid', $city_id)->get();
            $builder->where('city_id', $city_id);
        }
        $county_id = $request->input('county');
        if (isset($county_id)) {
            $params['county_id'] = $county_id;
            $builder->where('county_id', $county_id);
        }
        $name = $request->input('name');
        if (isset($name)) {
            $params['name'] = $name;
            $builder->where('name','like', "%{$name}%");
        }
        $info           = $builder->paginate($this->pageSize);
        $params['info'] = $info;
        return view('communities.index', $params);
    }

    public function select(Request $request)
    {
        $community_id = $request->id;
        $cookie = cookie('community_id',$community_id);
        return redirect()->intended()->cookie($cookie);
    }

    public function all()
    {
        $cookie = cookie('community_id',null);
        return redirect()->intended()->cookie($cookie);
    }

    public function getByCountyId(Request $request)
    {
        $county_id = $request->input('county_id');
        $info = Communities::query()->where('county_id',$county_id)->get();
        return response()->json($info);
    }
}
